package com.webmarmun.kamata;

import android.app.Activity;
import android.os.Bundle;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Calendar;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;


import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;

	
	

  

public class KamataActivity extends Activity {
	
	private Button calculate;
	private Button mPickDate;
	private TextView cifra;
	private TextView mDateDisplay;
	private Button mPickDate2;
	private TextView mDateDisplay2;
	static final int DATE_DIALOG_ID = 0;
	static final int DATE_DIALOG_ID2 = 1;
	private int mYear;
	private int mMonth;
	private int mDay;
	private int mYear2;
	private int mMonth2;
	private int mDay2;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ImageView image = (ImageView) findViewById(R.id.test_image);
        
        
        
        calculate = (Button) findViewById(R.id.button1);
        calculate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
            	if(haveNetworkConnection()){
            		Calculate();
            	}else{
        			
        			System.out.println("No network connection");
        			
        		}
            }
         });
        
        
        cifra = (TextView) findViewById(R.id.editText0);
        cifra.setOnClickListener(new View.OnClickListener() { 

		      public void onClick(View v) {
		          cifra.setText("");
		      
		    } 
    });
       
        
        mDateDisplay = (TextView) findViewById(R.id.editText1);
        mPickDate = (Button) findViewById(R.id.button2);
        mDateDisplay.setVisibility(View.GONE);
        
        mDateDisplay2 = (TextView) findViewById(R.id.editText2);
        mDateDisplay2.setVisibility(View.GONE);
        mPickDate2 = (Button) findViewById(R.id.button3);
        
        mPickDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });
        
        
        
      
        
        mPickDate2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID2);
            }
        });
        
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        
        mYear2 = c.get(Calendar.YEAR);
        mMonth2 = c.get(Calendar.MONTH);
        mDay2 = c.get(Calendar.DAY_OF_MONTH);

        // display the current date (this method is below)
        updateDisplay();
        updateDisplay2();
        
        
        
      
        
    }
    
    
    private void updateDisplay() {
    	mDateDisplay.setText(
            new StringBuilder()
                    // Month is 0 based so add 1
                    .append(mMonth + 1).append("-")
                    .append(mDay).append("-")
                    .append(mYear).append(" "));
    }
    
    private void updateDisplay2() {
    	mDateDisplay2.setText(
            new StringBuilder()
                    // Month is 0 based so add 1
                    .append(mMonth2 + 1).append("-")
                    .append(mDay2).append("-")
                    .append(mYear2).append(" "));
    }
    
    
    private DatePickerDialog.OnDateSetListener mDateSetListener =
	        new DatePickerDialog.OnDateSetListener() {
	                        @Override
	                        public void onDateSet(DatePicker view, int year, int monthOfYear,
	                                        int dayOfMonth) {
	                                mYear = year;
	                mMonth = monthOfYear;
	                mDay = dayOfMonth;
	                
	                mPickDate.setVisibility(View.GONE);
	                mDateDisplay.setVisibility(1);
	                mDateDisplay.setText("");
	                
	                updateDisplay();
	                                
	                        }
	        };
	        
	        
	        protected Dialog onCreateDialog(int id) {
	            switch (id) {
	            case DATE_DIALOG_ID:
	                return new DatePickerDialog(this,mDateSetListener,mYear, mMonth, mDay);
	            case DATE_DIALOG_ID2:
	                return new DatePickerDialog(this, mDateSetListener2,mYear2, mMonth2, mDay2);
	            }
	            return null;
	        }
	        
	        View.OnClickListener buttonhandler=new View.OnClickListener() { 

		 		 
	 		      public void onClick(View v) {
	 		          Intent myIntent1 = new Intent(KamataActivity.this, KamataActivity.class);
	 		         KamataActivity.this.startActivity(myIntent1);
	 		      
	 		    } 
	        };
	        
	        private DatePickerDialog.OnDateSetListener mDateSetListener2 =
	    	        new DatePickerDialog.OnDateSetListener() {
	    	                        @Override
	    	                        public void onDateSet(DatePicker view, int year2, int monthOfYear2,
	    	                                        int dayOfMonth2) {
	    	                                mYear2 = year2;
	    	                mMonth2 = monthOfYear2;
	    	                mDay2 = dayOfMonth2;
	    	               
	    	                mPickDate2.setVisibility(View.GONE);
	    	                mDateDisplay2.setVisibility(1);
	    	                mDateDisplay2.setText("");
	    	                updateDisplay2();
	    	                                
	    	                        }
	    	        };
	    	        
	    	        
	    	       
	    	        
	    	        View.OnClickListener buttonhandler2=new View.OnClickListener() { 

	    		 		 
	    	 		      public void onClick(View v) {
	    	 		          Intent myIntent2 = new Intent(KamataActivity.this, KamataActivity.class);
	    	 		         KamataActivity.this.startActivity(myIntent2);
	    	 		      
	    	 		    } 
	    	        };
    
    
    
	    	        
	    	        public void Calculate(){
	    	        	String datumOD=URLEncoder.encode(mDateDisplay.getText().toString().trim());
	    	        	String datumDO=URLEncoder.encode(mDateDisplay2.getText().toString().trim());
	    	        	String dug=URLEncoder.encode(cifra.getText().toString().trim());
	    	        	cifra.setText("");
	    	        	cifra.setVisibility(View.GONE);
	    	        	mDateDisplay.setText("");
	    	        	mDateDisplay.setVisibility(View.GONE);
	    	        	mDateDisplay2.setText("");
	    	        	mDateDisplay2.setVisibility(View.GONE);
	    	        		InputStream is = null;
	    	        		
	    	        		
							try {
								
							
		    	                HttpClient client = new DefaultHttpClient();  
		    	                String getURL = "http://prvisud.rs/kamata/apikamata.php?from="+datumOD+"&to="+datumDO+"&base="+dug+"";
		    	                //String safeUrl = URLEncoder.encode(getURL);
		    	                //System.out.println(getURL);
		    	                HttpGet get = new HttpGet(getURL);
		    	                HttpResponse responseGet = client.execute(get);  
		    	                HttpEntity resEntityGet = responseGet.getEntity(); 
		    	               
		    	                if (resEntityGet != null || resEntityGet.toString().length() < 2) {  
		    	               
		    	              	                	
		    	                     final String response= EntityUtils.toString(resEntityGet);
		    	                  	    	                	
	    	                     AlertDialog alertDialog = new AlertDialog.Builder(KamataActivity.this).create();
		    	                     alertDialog.setTitle("Резултат");
		    	                     alertDialog.setMessage(response);
		    	                     alertDialog.setButton("У реду", new DialogInterface.OnClickListener() {
	    	                         public void onClick(DialogInterface dialog, int which) {
		    	                         cifra.setVisibility(1);
	    	                        	 mPickDate.setVisibility(1);
	    	                        	 mPickDate2.setVisibility(1);
	    	                        	 //System.out.println("rezultat je >"+response.length());
		    	                    
	    	                       } }); 
		    	                     alertDialog.show();
		    	                   }else{
		    	                	   AlertDialog alertDialog2 = new AlertDialog.Builder(KamataActivity.this).create();
			    	                     alertDialog2.setTitle("Грешка");
			    	                     alertDialog2.setMessage("Дошло је до грешке, молимо пробајте поново ...");
			    	                     alertDialog2.setButton("У реду", new DialogInterface.OnClickListener() {
		    	                         public void onClick(DialogInterface dialog, int which) {
			    	                         cifra.setVisibility(1);
		    	                        	 mPickDate.setVisibility(1);
		    	                        	 mPickDate2.setVisibility(1);
		    	                        	 
			    	                    
		    	                       } }); 
		    	                	   
		    	                   }
		    	        } catch (Exception e) {
		    	            e.printStackTrace();
		    	            
		    	        }
	    	        		
							

	    	      }
	    	        
	    	        private boolean haveNetworkConnection() {
					    boolean haveConnectedWifi = false;
					    boolean haveConnectedMobile = false;

					    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
					    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
					    for (NetworkInfo ni : netInfo) {
					        if (ni.getTypeName().equalsIgnoreCase("WIFI"))
					            if (ni.isConnected())
					                haveConnectedWifi = true;
					        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
					            if (ni.isConnected())
					                haveConnectedMobile = true;
					    }
					    return haveConnectedWifi || haveConnectedMobile;
					}
	    	        
	    	        
	    	        
    
}
        
